package psn.zjk.career.interview.algorithm;

/**
 * @USER white
 * @DATETIME 2021/1/8 18:41
 */
public class ListNode {
    int val;
    ListNode next = null;

    ListNode() {

    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(val);
        ListNode tmp =next;
        while (tmp!=null){
            sb.append(" ").append(tmp.val);
            tmp=tmp.next;
        }
        return sb.toString();
    }

    public ListNode append() {
        int x = val;
        next = new ListNode(++x);
        return next;
    }

    public static ListNode build(int[] vals) {
        return next(vals, 0);
    }

    private static ListNode next(int[] vals, int index) {
        if (vals.length == index + 1) {
            return new ListNode(vals[index]);
        }
        return new ListNode(vals[index], next(vals, index + 1));
    }
}
